home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13238 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  43 lines

  1. Path: li.net!jeremy
  2. From: jeremy@newshost.li.net (Jeremy Markman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Recursion Question
  5. Date: 5 Apr 1996 14:26:19 GMT
  6. Organization: LI Net (Long Island Network)
  7. Message-ID: <4k3aib$sf@linet06.li.net>
  8. References: <4k14o1$2k2@isis.fiu.edu>
  9. NNTP-Posting-Host: linet04.li.net
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Mark Romano (mark@serss1.fiu.edu) wrote:
  13. : I am trying to find some recursive functions that will convert a number into 
  14. : a binary. I need one that will print out the numbers as they are 
  15. : generated and I also need one that will hold the binary digits in memory 
  16. : and then printed out with a single printf statement.  Can any one help??
  17.  
  18. char *tobinary(int decimal)
  19.  {
  20.   int remainder;
  21.   char *binary;
  22.   char *binary2;
  23.  
  24.   if (decimal == 0)
  25.     return("");
  26.   binary = tobinary(decimal / 2);
  27.   binary2 = malloc(strlen(binary) + 2);
  28.   strcpy(binary2,binary);
  29.   binary2[strlen(binary2) + 1] = '\0';
  30.   binary2[strlen(binary2)] = '0' + (decimal % 2);
  31.   return(binary2);
  32.  }
  33.  
  34. This is rough, as their will be some memory loss (I don't deallocate 
  35. memory, for instance) and I'm sure the code can be pared down, but this 
  36. is off the top of my head...
  37.  
  38. This uses the basic binary conversion algorithm where you keep dividing 
  39. the decimal number by 2, concatinating the remainder as the most 
  40. significant digit to the binary number.  Of course, since recursion turns 
  41. this around, you have to remember to concat. the remainder as the least 
  42. significant digit of the binary string returned...
  43.